<template>
  <div class="container">
    <Header :getGoods="getGoods" />
    <main class="main" @scroll="onScroll">
      <div class="main-top">
        <div class="main-top-left">
          <button class="prev-button" @click="prevSlide"><</button>
          <div class="carousel">
            <img :src="slides[currentIndex]" alt="Slide" />
          </div>
          <button class="next-button" @click="nextSlide">></button>
        </div>
        <div class="main-top-right">
          <div class="information">
            <div class="information-main">
              <div v-for="info in visibleInformation" :key="info.id" class="info-item"  @click="goToInformation(info.id)">
                <img :src="info.image" alt="Information Image" class="info-image" />
                <div class="info-content">
                  <p>{{ info.title }}</p>
                  <p class="info-time">{{ info.createTime }}</p>
                </div>
              </div>
            </div>
            <div class="information-page">
              <button class="page-button" @click="goToPage(1)" :disabled="infoPage === 1">首页</button>
              <button class="page-button" @click="prevPage" :disabled="infoPage === 1">&lt;</button>
              <span>当前为第 {{ infoPage }} 页</span>
              <button class="page-button" @click="nextPage" :disabled="infoPage * perInfoPage >= information.length">&gt;</button>
              <button class="page-button" @click="goToPage(totalPages)" :disabled="infoPage * perInfoPage >= information.length">尾页</button>
            </div>
          </div>
        </div>
      </div>
      <div class="main-bottom">
        <GoodsList :goods="visibleGoods" />
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import Header from './Header.vue';
import GoodsList from './GoodsList.vue';
import { getGoodsFromAPI } from '../utils';
import { onUnmounted } from 'vue';
import '../css/index.css';
import '../css/goods.css';
import { useRouter } from 'vue-router';


interface Information {
  id: number;
  title: string;
  content: string;
  createUser: number;
  createTime: string;
  image: string;
}

const searchByname = ref(''); 
const goods = ref([]);
const visibleGoods = ref([]);
const information = ref<Information[]>([]);
const visibleInformation = ref<Information[]>([]);
const currentIndex = ref<number>(0);
const slides = ref<string[]>([
  '/public/img/persona5.png', 
  '/public/img/TearsOfKingdom.png', 
  '/public/img/starField.png',
  '/public/img/EldenRing.png',
  '/public/img/blackMityWukong.png'
]);
const totalSlides = ref<number>(slides.value.length);
let autoPlayInterval: number | null = null;
let page = ref<number>(1);
const router = useRouter();
const perPage = 10;
const perInfoPage = 8; // 每页显示 8 条信息
const infoPage = ref<number>(1);
const getGoodsLink = 'http://localhost:8080/goods/allGoods';
const getInformationLink = 'http://localhost:8080/information/InformationPage';

const loadMoreGoods = () => {
  const start = (page.value - 1) * perPage;
  const end = page.value * perPage;
  visibleGoods.value.push(...goods.value.slice(start, end));
  page.value++;
};

// 不再在初始时调用
const loadMoreInformation = () => {
  const start = (infoPage.value - 1) * perInfoPage;
  const end = infoPage.value * perInfoPage;
  visibleInformation.value.push(...information.value.slice(start, end));
  infoPage.value++;
};

const nextSlide = () => {
  currentIndex.value = (currentIndex.value + 1) % totalSlides.value;
};

const prevSlide = () => {
  currentIndex.value = (currentIndex.value - 1 + totalSlides.value) % totalSlides.value;
};

const totalPages = computed(() => Math.ceil(information.value.length / perInfoPage));

const startAutoPlay = () => {
  autoPlayInterval = setInterval(() => {
    nextSlide();
  }, 6000);
};

const onScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  if (target.scrollTop + target.clientHeight >= target.scrollHeight) {
    loadMoreGoods();
  }
};

const getGoods = async (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => {
  try {
    page.value = 1;
    goods.value = [];
    visibleGoods.value = [];
    await getGoodsFromAPI(filterObject, getGoodsLink, goods, loadMoreGoods);
  } catch (error: any) {
    console.error('Error fetching goods:', error);
  }
};

const getInformation = async () => {
  const InformationPageDto = {
    page: 1,
    pageSize: 20 // 总的数据量较大时，可以设置为更大的值，后续会通过 loadMoreInformation 分页加载
  };
  try {
    const response = await axios.post(getInformationLink, InformationPageDto, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    information.value = response.data.data.records;
    loadInformation(); // 初始化时加载第一页信息
  } catch (error) {
    console.error('Error fetching information:', error);
  }
};

// 更新逻辑，初始化只加载第一页
const loadInformation = () => {
  const start = (infoPage.value - 1) * perInfoPage;
  const end = infoPage.value * perInfoPage;
  visibleInformation.value = information.value.slice(start, end);
};

const goToPage = (pageNumber: number) => {
  infoPage.value = pageNumber;
  loadInformation();
};

const prevPage = () => {
  if (infoPage.value > 1) {
    infoPage.value--;
    loadInformation();
  }
};

const nextPage = () => {
  if (infoPage.value * perInfoPage < information.value.length) {
    infoPage.value++;
    loadInformation();
  }
};

const goToInformation =(id:number) =>{
  router.push({ path: `/inforMationDetail/${id}` });
}

onMounted(() => {
  getGoods({
    name: searchByname.value,
    platform: '',
    sortType: '',
    categoriesId: 0,
  });
  startAutoPlay();
  getInformation(); // 初始化只加载第一页
});

onUnmounted(() => {
  if (autoPlayInterval) {
    clearInterval(autoPlayInterval);
  }
});
</script>
